<template>
  <view class="main-container">
    <view class="interface">
      <text class="corner-text top-left" style="font-size: 35rpx">设备</text>
      <text
        class="corner-text top-right"
        v-if="!connectionStatus"
        @click="initBlue"
        >搜索设备并连接</text
      >
      <text class="corner-text top-right" v-else @click="disConnectd"
        >点击断开连接</text
      >
      <!-- <image src="../../static/images/blood_oxygen.png"></image> -->
      <text class="corner-text bottom-left"
        >指压式脉搏血氧仪\n <text style="color: #808080">A0J-30B</text></text
      >
      <text
        class="corner-text bottom-right"
        style="font-size: 50rpx; font-weight: bolder"
      >
        ·<text
          style="color: black; font-size: 30rpx; font-weight: normal"
          v-if="!connectionStatus"
        >
          未连接</text
        >
        <text
          v-else
          style="color: black; font-size: 30rpx; font-weight: normal"
          @click="getCharacteristics"
        >
          已连接,点击开始测量</text
        >
      </text>
    </view>
    <uni-popup ref="popup" :mask-click="true" @close="handlePopupClose">
      <device-connection
        :device-name="deviceName"
        @send="connetionCallBack"
        ref="deviceConnection"
      >
      </device-connection>
      <!-- <button @click="close">关闭</button> -->
    </uni-popup>
    <view class="container">
      <oxygen-testing
        :pulseRate="pulseRate"
        :perfusionIndex="perfusionIndex"
        :myChartData="charData"
        :oxygenSaturation="oxygenSaturation"
      ></oxygen-testing>
    </view>
  </view>
</template>

<script>
import { postOxygenInfo } from "../../api/post_oxygen_info";
export default {
  onShow() {
    this.oxygenInfo = {
      averageOxygen: 0,
      averagePluseRate: 0,
      beginTime: "",
      endTime: "",
      lowerTime: 0,
      lowestOxygen: 0,
      lowestPluseRate: 0,
      lowestPrefusionIndex: "",
      oxygenValues: "",
      pluseRateValues: "",
      pluseWaveform: "",
      recordTime: 0,
      updatedAt: "",
      userId: 0,
    };
    this.flag = false;
  },
  data() {
    return {
      oxygenInfo: {
        averageOxygen: 0,
        averagePluseRate: 0,
        beginTime: "",
        endTime: "",
        id: 0,
        lowerTime: 0,
        lowestOxygen: 100,
        lowestPluseRate: 300,
        lowestPrefusionIndex: "",
        oxygenValues: "",
        pluseRateValues: "",
        pluseWaveform: "",
        recordTime: 0,
        updatedAt: "",
        userId: "0",
      },
      flag: false,
      deviceName: "血氧仪器",
      heartRates: [],
      pulseRate: 0,
      perfusionIndex: 0,
      oxygenSaturation: 0,
      oxygenSaturations: [],
      piIndexes: [],
      connectionStatus: false,
      bluetoothDevices: [], // 存储蓝牙设备列表
      serviceId: "",
      notifyId: "",
      deviceId: "", // 0xFFE0，0xFFE1 0xFFE2
      valueList: [], // 这里的话要对第三个数除10
      begenTime: "",
      endTime: "",
      charData: {
        categories: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
        series: [
          {
            name: " 心电",
            linearColor: [
              [0, "#1890FF"],
              [0.25, "#00B5FF"],
              [0.5, "#00D1ED"],
              [0.75, "#00E6BB"],
              [1, "#90F489"],
            ],
            setShadow: [3, 8, 10, "#1890FF"],
            data: [89, 88, 87, 89, 89, 88, 88, 98, 78, 89],
          },
        ],
      },
    };
  },
  methods: {
    // 参数1为文件名称 参数2是文件内容 参数3是回调参数
    saveFile(fileName, fileInfo) {
      // 请求本地文件系统对象
      plus.io.requestFileSystem(
        plus.io.PUBLIC_DOWNLOADS, // 文件系统中的根目录
        (fs) => {
          // 创建或打开文件, fs.root是根目录操作对象,直接fs表示当前操作对象
          fs.root.getFile(
            fileName,
            {
              create: true, // 文件不存在则创建
            },
            (fileEntry) => {
              // 文件在手机中的路径
              console.log("最后文件在手机中的路径========", fileEntry.fullPath);
              fileEntry.createWriter((writer) => {
                // 写入文件成功完成的回调函数
                writer.onwrite = (e) => {
                  console.log("写入数据成功");
                };
                // 写入数据
                writer.write(JSON.stringify(fileInfo));
              });
            },
            (e) => {
              callback(false);
              console.log("报错111", "getFile failed: " + e.message);
            }
          );
        },
        (e) => {
          console.log("报错222", e.message);
          callback(false);
        }
      );
    },
    connetionCallBack(deviceId, serviceId) {
      this.deviceId = deviceId;
      this.serviceId = serviceId;
      console.log("Received deviceId:", deviceId);
      console.log("Received serviceUuid:", serviceId);
      this.connectionStatus = true;
    },
    handlePopupClose() {
      this.$refs.popup.close();
      this.stopBluetoothDiscovery();
    },
    disConnectd() {
      this.connectionStatus = false;
      this.closeConnection();
    },
    initBlue() {
      uni.openBluetoothAdapter({
        success: (res) => {
          console.log("初始化蓝牙成功");
          console.log(res);
          this.$refs.popup.open("center");
          this.$refs.deviceConnection.init();
        },
        fail: (err) => {
          console.log("初始化蓝牙失败");
          console.error(err);
        },
      });
    },
    stopBluetoothDiscovery() {
      uni.stopBluetoothDevicesDiscovery({
        success: (res) => {
          console.log("蓝牙搜索已停止", res);
          // this.bluetoothDevices = [];
        },
        fail: (err) => {
          console.error("停止蓝牙搜索失败", err);
        },
      });
    },
    notifyDevice(notifyId) {
      console.log("进入了消息监听，下面是特征值");
      console.log(notifyId);
      console.log("正在进行监听数据");
      uni.notifyBLECharacteristicValueChange({
        state: true,
        deviceId: this.deviceId, // 设备ID，在【4】里获取到
        serviceId: this.serviceId, // 服务UUID，在【6】里能获取到
        characteristicId: notifyId, // 特征值，在【7】里能获取到
        success: (res) => {
          console.log("监听成功");
          console.log(res);
          // 接受消息的方法
          this.listenValueChange();
        },
        fail: (err) => {
          console.log("监听失败，原因如下");
          console.error(err);
        },
      });
    },
    getCharacteristics() {
      uni.getBLEDeviceCharacteristics({
        deviceId: this.deviceId, // 设备ID，在【4】里获取到
        serviceId: this.serviceId, // 服务UUID，在【6】里能获取到
        success: (res) => {
          this.characteristicIdList = res.characteristics;
          for (let i = 0; i < this.characteristicIdList.length; i++) {
            // console.log(this.characteristicIdList[i])
            if (this.characteristicIdList[i].properties.notify) {
              this.characteristicId = this.characteristicIdList[i].uuid;
              this.notifyId = this.characteristicIdList[i].uuid;
              console.log(this.notifyId);
              this.notifyDevice(this.notifyId);
              console.log("获取特征值成功且赋值成功");
              break;
            }
          }
        },
        fail: (err) => {
          console.error("获取特征值失败");
          console.error(err);
        },
      });
    },
    getTime() {
      // 创建一个新的日期对象
      var now = new Date();

      // 获取年份
      var year = now.getFullYear();

      // 获取月份（0-11）
      var month = now.getMonth() + 1;

      // 获取日期
      var date = now.getDate();

      // 获取小时
      var hours = now.getHours();

      // 获取分钟
      var minutes = now.getMinutes();

      // 获取秒钟
      var seconds = now.getSeconds();

      // 格式化输出时间
      var formattedTime =
        year +
        "-" +
        month +
        "-" +
        date +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        seconds;

      // 在控制台打印时间
      return formattedTime;
    },
    listenValueChange() {
      console.log("监听中...");
      this.oxygenInfo.beginTime = this.getTime();
      uni.onBLECharacteristicValueChange((res) => {
        // 结果里有个value值，该值为 ArrayBuffer 类型，所以在控制台无法用肉眼观察到，必须将该值转换为16进制
        let resHex = this.ab2hex(res.value);
        // console.log(resHex);
        if (resHex.substring(0, 2) == "81") {
          this.oxygenInfo.recordTime++;
          // 只有81的数据是我们所需要的
          this.valueList = this.hexToDecimal(resHex);
          this.valueList[2] /= 10;
          this.heartRates.push(this.valueList[0]);
          if (this.valueList[1] < 90) {
            this.oxygenInfo.lowerTime++;
          }
          this.oxygenSaturations.push(this.valueList[1]);
          this.piIndexes.push(this.valueList[2]);

          this.pulseRate = this.valueList[0];
          this.oxygenSaturation = this.valueList[1];
          this.perfusionIndex = this.valueList[2];
          if (this.perfusionIndex < this.oxygenInfo.lowestPrefusionIndex) {
            this.oxygenInfo.lowestPrefusionIndex = this.perfusionIndex;
          }
          if (this.pulseRate < this.oxygenInfo.lowestPluseRate) {
            this.oxygenInfo.lowestPluseRate = this.pulseRate;
          }
          if (this.oxygenSaturation < this.oxygenInfo.lowestOxygen) {
            this.oxygenInfo.lowestOxygen = this.oxygenSaturation;
          }
        } else {
          const temp = this.hexToDecimal(resHex);
          // console.log(temp)
          this.charData.series.data = temp.slice(1, 11);
          console.log(this.charData.series.data);
        }
      });
    },
    addOxygen() {
      if (this.$store.state.currId != 0) {
        // 计算氧气饱和度的平均值
        console.log(this.oxygenSaturations);
        const sumOxygen = this.oxygenSaturations.reduce(
          (accumulator, currentValue) => accumulator + currentValue,
          0
        );
        const averageOxygen =
          this.oxygenSaturations.length > 0
            ? sumOxygen / this.oxygenSaturations.length
            : 0;
        // 计算心率的平均值
        const sumHeartRates = this.heartRates.reduce(
          (accumulator, currentValue) => accumulator + currentValue,
          0
        );
        const averagePluseRate =
          this.heartRates.length > 0
            ? sumHeartRates / this.heartRates.length
            : 0;
        this.oxygenInfo.averageOxygen = averageOxygen;
        this.averagePluseRate = averagePluseRate;
        this.oxygenInfo.oxygenValues = "" + this.oxygenSaturations;
        this.oxygenInfo.pluseRateValues = "" + this.heartRates;
        this.oxygenInfo.pluseWaveform = "" + this.piIndexes;
        this.oxygenInfo.userId = this.$store.state.currId;
        postOxygenInfo(this.oxygenInfo)
          .then((res) => {
            console.log(res);
          })
          .catch((err) => {
            console.log(err);
            console.log("添加失败");
          });
      }
    },
    closeConnection() {
      console.log("正在断开连接");
      this.oxygenInfo.endTime = this.getTime();
      // 保存 this 的引用
      const self = this;
      uni.closeBLEConnection({
        deviceId: this.deviceId,
        success: (res) => {
          console.log(res);
          console.log("断开连接成功");
          self.addOxygen();
        },
        fail: (err) => {
          console.log(err);
          console.log("断开连接失败");
        },
      });
    },
    ab2hex(buffer) {
      const hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
          return ("00" + bit.toString(16)).slice(-2);
        }
      );
      return hexArr.join("");
    },
    hexToDecimal(hexString) {
      const decimalList = [];
      for (let i = 2; i < hexString.length; i += 2) {
        const hexValue = hexString.substring(i, i + 2);
        const decimalValue = parseInt(hexValue, 16);
        decimalList.push(decimalValue);
      }
      return decimalList;
    },
  },
};
</script>

<style>
.main-container {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  height: 60vh;
}
.interface {
  /* position: absolute; */
  flex-wrap: wrap;
  position: absolute;
  width: 85%;
  height: 25%;
  left: 7%;
  top: 28%;
  background: #ffffff;
  box-shadow: 4px 4px 4px #94d6e2;
  border-radius: 15px;
}

.corner-text {
  font-size: 12px;
  position: absolute;
}

.top-left {
  top: 10px;
  left: 10px;
}

.top-right {
  top: 10px;
  right: 10px;
  color: #48c454; /* 绿色文本 */
}

.bottom-left {
  bottom: 10px;
  left: 10px;
}

.bottom-right {
  bottom: 10px;
  right: 10px;
  color: #48c454; /* 绿色文本 */
}

.data-card {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 100%;
  background-color: #ffffff;
  margin-top: 50%;
}

.pressure {
  display: flex;
  justify-content: center;
  width: 100%;
  flex-direction: row;
  /*   align-items: center; */
}

.vvv {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20rpx;
  margin-bottom: 20rpx;
  margin-right: 40rpx;
  margin-left: 40rpx;
}

.vertical-line {
  height: 80rpx; /* 控制竖线的高度 */
  width: 2px; /* 控制竖线的宽度 */
  background-color: #cccccc;
  margin: 0 20rpx;
}
.label {
  font-size: 12px;
  color: #808080; /* 灰色文本 */
}
.container {
  margin-top: 378rpx;
  margin-right: 8vw;
}

.row {
  display: flex;
}

.item {
  margin-right: 10px;
}
</style>
